<script setup lang="ts">
  import { computed } from 'vue'
  import { ElAside, ElButton } from 'element-plus'
  import { Icon } from '@iconify/vue'
  import ChevronRight from '@iconify/icons-line-md/chevron-right'
  import ChevronLeft from '@iconify/icons-line-md/chevron-left'
  import { StrUtil } from '@xtail/core'
  import { WatchSizeStrategyConst, SWatchSize } from '@xtail/vue3'
  import { ResponsiveWidthConst } from '@xtail/ui'
  import { LayoutSideResponsivePropsType } from './types'

  defineOptions({
    name: 'XLayoutSideResponsive'
  })

  const props = withDefaults(defineProps<LayoutSideResponsivePropsType>(), {
    width: '202px',
    collapseWidth: '56px',
    showTrigger: true,
    triggerProps: {} as any,
    collapseSpeed: 300,
    watchSizeProps: {} as any,
    className: '',
    style: ''
  })

  const collapse = defineModel<boolean>('collapse', { default: false })
  const toggleCollapsed = () => (collapse.value = !collapse.value)
  const widthUpdateHandlerDefault = (size: number) => {
    collapse.value = size <= ResponsiveWidthConst.sm
  }

  const styleComputed = computed(() => {
    if (StrUtil.isStr(props.style)) {
      return `transition: width ${props.collapseSpeed}ms ease-in-out; ${props.style}`
    } else {
      return {
        transition: `width ${props.collapseSpeed}ms ease-in-out`,
        ...props.style
      }
    }
  })
</script>

<template>
  <s-watch-size
    v-bind="{
      ...watchSizeProps,
      strategy: watchSizeProps.strategy ?? WatchSizeStrategyConst.WINDOW,
      widthUpdateHandler: watchSizeProps.widthUpdateHandler ?? widthUpdateHandlerDefault
    }"
  >
    <el-aside
      class="x-layout-side-resize"
      :class="className"
      :width="collapse ? collapseWidth : width"
      :style="styleComputed"
    >
      <div class="x-layout-side-resize__content-container">
        <div class="x-layout-side-resize__content">
          <slot name="content" :collapse="collapse" :toggle-collapse="toggleCollapsed" />
        </div>
      </div>
      <div v-if="showTrigger" class="x-layout-side-resize__trigger">
        <slot name="trigger" :collapse="collapse" :toggle-collapse="toggleCollapsed">
          <el-button
            class="x-layout-side-resize__trigger-btn"
            v-bind="{
              ...triggerProps,
              text: triggerProps.text ?? true
            }"
            @click="toggleCollapsed"
          >
            <template #icon>
              <slot name="trigger-icon">
                <Icon :icon="collapse ? ChevronRight : ChevronLeft" />
              </slot>
            </template>
          </el-button>
        </slot>
      </div>
    </el-aside>
  </s-watch-size>
</template>

<style lang="scss">
  @use './style' as *;
</style>
